#include "library.h"

// 添加图书 (管理员功能)
void addBook() {
    if (currentUser == NULL || currentUser->power != USER_ROOT) {
        printf("权限不足!\n");
        return;
    }

    Book newBook;
    printf("\n--- 添加新图书 ---\n");
    printf("书名: ");
    fgets(newBook.bookname, MAX_bookname_LEN, stdin);
    newBook.bookname[strcspn(newBook.bookname, "\n")] = '\0';
    printf("作者: ");
    fgets(newBook.author, MAX_AUTHOR_LEN, stdin);
    newBook.author[strcspn(newBook.author, "\n")] = '\0';
    printf("出版社: ");
    fgets(newBook.publisher, MAX_PUBLISHER_LEN, stdin);
    newBook.publisher[strcspn(newBook.publisher, "\n")] = '\0';
    printf("类别: ");
    fgets(newBook.category, MAX_CATEGORY_LEN, stdin);
    newBook.category[strcspn(newBook.category, "\n")] = '\0';
    printf("出版年份: ");
    scanf("%d", &newBook.years);
    clearInputBuffer();

    newBook.status = BOOK_AVAILABLE;
    newBook.borrowerId = -1;
    newBook.borrowDate = 0;
    newBook.returnDate = 0;

    // 插入新图书
    sqlite3_stmt *stmt;
    const char *sql = "INSERT INTO book (bookname, author, publisher, category, years, status, borrowerId, borrowDate, returnDate) "
                     "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
    int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "SQL错误: %s\n", sqlite3_errmsg(db));
        return;
    }

    sqlite3_bind_text(stmt, 1, newBook.bookname, -1, SQLITE_STATIC);
    sqlite3_bind_text(stmt, 2, newBook.author, -1, SQLITE_STATIC);
    sqlite3_bind_text(stmt, 3, newBook.publisher, -1, SQLITE_STATIC);
    sqlite3_bind_text(stmt, 4, newBook.category, -1, SQLITE_STATIC);
    sqlite3_bind_int(stmt, 5, newBook.years);
    sqlite3_bind_int(stmt, 6, newBook.status);
    sqlite3_bind_int(stmt, 7, newBook.borrowerId);
    sqlite3_bind_int64(stmt, 8, newBook.borrowDate);
    sqlite3_bind_int64(stmt, 9, newBook.returnDate);
    rc = sqlite3_step(stmt);
    if (rc != SQLITE_DONE) {
        fprintf(stderr, "添加图书失败: %s\n", sqlite3_errmsg(db));
    } else {
        printf("图书添加成功! 图书ID: %lld\n", sqlite3_last_insert_rowid(db));
    }
    sqlite3_finalize(stmt);
}

// 删除图书 (管理员功能)
void deleteBook() {
    if (currentUser == NULL || currentUser->power != USER_ROOT) {
        printf("权限不足!\n");
        return;
    }

    int bookId;
    printf("\n--- 删除图书 ---\n");
    printf("请输入要删除的图书ID: ");
    scanf("%d", &bookId);
    clearInputBuffer();

    // 检查图书是否存在
    sqlite3_stmt *stmt;
    const char *sql = "SELECT COUNT(*) FROM book WHERE id = ?";
    int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "SQL错误: %s\n", sqlite3_errmsg(db));
        return;
    }

    sqlite3_bind_int(stmt, 1, bookId);
    rc = sqlite3_step(stmt);
    if (rc == SQLITE_ROW && sqlite3_column_int(stmt, 0) == 0) {
        printf("未找到ID为%d的图书!\n", bookId);
        sqlite3_finalize(stmt);
        return;
    }
    sqlite3_finalize(stmt);

    // 删除图书
    sql = "DELETE FROM book WHERE id = ?";
    rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "SQL错误: %s\n", sqlite3_errmsg(db));
        return;
    }

    sqlite3_bind_int(stmt, 1, bookId);
    rc = sqlite3_step(stmt);
    if (rc != SQLITE_DONE) {
        fprintf(stderr, "删除失败: %s\n", sqlite3_errmsg(db));
    } else {
        printf("图书删除成功!\n");
    }
    sqlite3_finalize(stmt);
}

// 修改图书信息 (管理员功能)
void modifyBook() {
    if (currentUser == NULL || currentUser->power != USER_ROOT) {
        printf("权限不足!\n");
        return;
    }

    int bookId;
    printf("\n--- 修改图书信息 ---\n");
    printf("请输入要修改的图书ID: ");
    scanf("%d", &bookId);
    clearInputBuffer();

    // 获取当前图书信息
    sqlite3_stmt *stmt;
    const char *sql = "SELECT bookname, author, publisher, category, years FROM book WHERE id = ?";
    int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "SQL错误: %s\n", sqlite3_errmsg(db));
        return;
    }

    sqlite3_bind_int(stmt, 1, bookId);
    rc = sqlite3_step(stmt);
    if (rc != SQLITE_ROW) {
        printf("未找到ID为%d的图书!\n", bookId);
        sqlite3_finalize(stmt);
        return;
    }

    Book book;
    book.id = bookId;
    strcpy(book.bookname, (const char*)sqlite3_column_text(stmt, 0));
    strcpy(book.author, (const char*)sqlite3_column_text(stmt, 1));
    strcpy(book.publisher, (const char*)sqlite3_column_text(stmt, 2));
    strcpy(book.category, (const char*)sqlite3_column_text(stmt, 3));
    book.years = sqlite3_column_int(stmt, 4);
    sqlite3_finalize(stmt);

    printf("当前图书信息:\n");
    printBookDetails(&book);
    printf("\n请输入新的信息 (留空则保持不变):\n");

    char input[MAX_bookname_LEN];
    printf("书名: ");
    fgets(input, MAX_bookname_LEN, stdin);
    input[strcspn(input, "\n")] = '\0';
    if (strlen(input) > 0) {
        strcpy(book.bookname, input);
    }

    printf("作者: ");
    fgets(input, MAX_AUTHOR_LEN, stdin);
    input[strcspn(input, "\n")] = '\0';
    if (strlen(input) > 0) {
        strcpy(book.author, input);
    }

    printf("出版社: ");
    fgets(input, MAX_PUBLISHER_LEN, stdin);
    input[strcspn(input, "\n")] = '\0';
    if (strlen(input) > 0) {
        strcpy(book.publisher, input);
    }

    printf("类别: ");
    fgets(input, MAX_CATEGORY_LEN, stdin);
    input[strcspn(input, "\n")] = '\0';
    if (strlen(input) > 0) {
        strcpy(book.category, input);
    }

    printf("出版年份: ");
    fgets(input, MAX_CATEGORY_LEN, stdin);
    input[strcspn(input, "\n")] = '\0';
    if (strlen(input) > 0) {
        book.years = atoi(input);
    }

    // 更新图书信息
    sql = "UPDATE book SET bookname = ?, author = ?, publisher = ?, category = ?, years = ? WHERE id = ?";
    rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "SQL错误: %s\n", sqlite3_errmsg(db));
        return;
    }

    sqlite3_bind_text(stmt, 1, book.bookname, -1, SQLITE_STATIC);
    sqlite3_bind_text(stmt, 2, book.author, -1, SQLITE_STATIC);
    sqlite3_bind_text(stmt, 3, book.publisher, -1, SQLITE_STATIC);
    sqlite3_bind_text(stmt, 4, book.category, -1, SQLITE_STATIC);
    sqlite3_bind_int(stmt, 5, book.years);
    sqlite3_bind_int(stmt, 6, book.id);
    rc = sqlite3_step(stmt);
    if (rc != SQLITE_DONE) {
        fprintf(stderr, "更新失败: %s\n", sqlite3_errmsg(db));
    } else {
        printf("图书信息修改成功!\n");
    }
    sqlite3_finalize(stmt);
}

// 查询图书
void searchBook() {
    int choice;
    char keyword[MAX_bookname_LEN];
    int found = 0;
    printf("\n--- 图书查询 ---\n");
    printf("1. 按书名查询\n");
    printf("2. 按作者查询\n");
    printf("3. 按类别查询\n");
    printf("请选择查询方式: ");
    scanf("%d", &choice);
    clearInputBuffer();

    printf("请输入查询关键词: ");
    fgets(keyword, MAX_bookname_LEN, stdin);
    keyword[strcspn(keyword, "\n")] = '\0';

    printf("\n--- 查询结果 ---\n");
    sqlite3_stmt *stmt;
    const char *sql;

    switch (choice) {
        case 1:
            sql = "SELECT id, bookname, author, publisher, category, years, status, borrowerId, returnDate FROM book WHERE bookname LIKE ?";
            break;
        case 2:
            sql = "SELECT id, bookname, author, publisher, category, years, status, borrowerId, returnDate FROM book WHERE author LIKE ?";
            break;
        case 3:
            sql = "SELECT id, bookname, author, publisher, category, years, status, borrowerId, returnDate FROM book WHERE category LIKE ?";
            break;
        default:
            printf("无效选择!\n");
            return;
    }

    int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "SQL错误: %s\n", sqlite3_errmsg(db));
        return;
    }

    char likePattern[MAX_bookname_LEN + 2];
    snprintf(likePattern, sizeof(likePattern), "%%%s%%", keyword);
    sqlite3_bind_text(stmt, 1, likePattern, -1, SQLITE_STATIC);

    while (sqlite3_step(stmt) == SQLITE_ROW) {
        Book book;
        book.id = sqlite3_column_int(stmt, 0);
        strcpy(book.bookname, (const char*)sqlite3_column_text(stmt, 1));
        strcpy(book.author, (const char*)sqlite3_column_text(stmt, 2));
        strcpy(book.publisher, (const char*)sqlite3_column_text(stmt, 3));
        strcpy(book.category, (const char*)sqlite3_column_text(stmt, 4));
        book.years = sqlite3_column_int(stmt, 5);
        book.status = (Booktatus)sqlite3_column_int(stmt, 6);
        book.borrowerId = sqlite3_column_int(stmt, 7);
        book.returnDate = sqlite3_column_int64(stmt, 8);
        printBookDetails(&book);
        found++;
    }
    sqlite3_finalize(stmt);

    if (found == 0) {
        printf("未找到匹配的图书!\n");
    }
}

// 列出所有图书
void listAllBook() {
    printf("\n--- 所有图书列表 ---\n");
    sqlite3_stmt *stmt;
    const char *sql = "SELECT id, bookname, author, publisher, category, years, status, borrowerId, returnDate FROM book";
    int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "SQL错误: %s\n", sqlite3_errmsg(db));
        return;
    }

    int count = 0;
    while (sqlite3_step(stmt) == SQLITE_ROW) {
        Book book;
        book.id = sqlite3_column_int(stmt, 0);
        strcpy(book.bookname, (const char*)sqlite3_column_text(stmt, 1));
        strcpy(book.author, (const char*)sqlite3_column_text(stmt, 2));
        strcpy(book.publisher, (const char*)sqlite3_column_text(stmt, 3));
        strcpy(book.category, (const char*)sqlite3_column_text(stmt, 4));
        book.years = sqlite3_column_int(stmt, 5);
        book.status = (Booktatus)sqlite3_column_int(stmt, 6);
        book.borrowerId = sqlite3_column_int(stmt, 7);
        book.returnDate = sqlite3_column_int64(stmt, 8);
        printBookDetails(&book);
        count++;
    }
    sqlite3_finalize(stmt);

    if (count == 0) {
        printf("图书馆中没有图书!\n");
    }
}

// 打印图书详情
void printBookDetails(Book* book) {
    printf("ID: %d\n", book->id);
    printf("书名: %s\n", book->bookname);
    printf("作者: %s\n", book->author);
    printf("出版社: %s\n", book->publisher);
    printf("类别: %s\n", book->category);
    printf("出版年份: %d\n", book->years);
    printf("状态: ");
    switch (book->status) {
        case BOOK_AVAILABLE:
            printf("可借阅\n");
            break;
        case BOOK_BORROWED:
            printf("已借出 (借阅者ID: %d)\n", book->borrowerId);
            printf("应还日期: %s", ctime(&book->returnDate));
            break;
        case BOOK_LOST:
            printf("已丢失\n");
            break;
    }
    printf("----------------------------\n");
}








void ViewRecords() {
    printf("\n=== 借阅记录查询 ===\n");
    
    // 构建查询SQL
    char sql[512];
    sqlite3_stmt *stmt;
    
    // 查询所有借阅记录
    strcpy(sql, "SELECT r.id, r.username, r.bookname, "
               "datetime(r.borrow_date, 'unixepoch', 'localtime') as borrow_date, "
               "datetime(r.return_date, 'unixepoch', 'localtime') as return_date, "
               "CASE WHEN r.return_date = 0 THEN '未归还' ELSE '已归还' END as status "
               "FROM record r "
               "ORDER BY r.borrow_date DESC");
    
    if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK) {
        printf("数据库查询错误: %s\n", sqlite3_errmsg(db));
        return;
    }
    
    printf("记录ID\t用户ID\t书名\t借出日期\t\t归还日期\t\t状态\n");
    printf("--------------------------------------------------------------------\n");
    
    while (sqlite3_step(stmt) == SQLITE_ROW) {
        printf("%d\t%d\t%s\t%s\t%s\t%s\n",
               sqlite3_column_int(stmt, 0),
               sqlite3_column_int(stmt, 1),
               sqlite3_column_text(stmt, 2),
               sqlite3_column_text(stmt, 3),
               sqlite3_column_text(stmt, 4),
               sqlite3_column_text(stmt, 5));
    }
    
    sqlite3_finalize(stmt);
    
    // 添加筛选和排序功能
    printf("\n【高级选项】\n");
    printf("1. 筛选未归还记录\n");
    printf("2. 筛选已归还记录\n");
    printf("3. 按借出日期升序排序\n");
    printf("4. 按借出日期降序排序\n");
    printf("5. 按用户名筛选\n");
    printf("6. 按书名筛选\n");
    printf("7. 返回\n");
    printf("请选择: ");
    
    int option;
    scanf("%d", &option);
    clearInputBuffer();
    
    if (option >= 1 && option <= 6) {
        char condition[256] = "";
        char order[50] = "ORDER BY r.borrow_date DESC";
        
        switch(option) {
            case 1: strcpy(condition, "WHERE r.return_date = 0"); break;
            case 2: strcpy(condition, "WHERE r.return_date > 0"); break;
            case 3: strcpy(order, "ORDER BY r.borrow_date ASC"); break;
            case 4: strcpy(order, "ORDER BY r.borrow_date DESC"); break;
            case 5: {
                char username[20];
                printf("请输入用户ID: ");
                scanf("%s", username);
                sprintf(condition, "WHERE r.username = %s", username);
                break;
            }
            case 6: {
                char bookname[100];
                printf("请输入书名(支持模糊查询): ");
                scanf(" %[^\n]", bookname);
                sprintf(condition, "WHERE r.bookname LIKE '%%%s%%'", bookname);
                break;
            }
        }
        
        // 重新构建查询SQL
        sprintf(sql, "SELECT r.id, r.username, r.bookname, "
                   "datetime(r.borrow_date, 'unixepoch', 'localtime') as borrow_date, "
                   "datetime(r.return_date, 'unixepoch', 'localtime') as return_date, "
                   "CASE WHEN r.return_date = 0 THEN '未归还' ELSE '已归还' END as status "
                   "FROM record r %s %s", condition, order);
        
        if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK) {
            printf("数据库查询错误: %s\n", sqlite3_errmsg(db));
            return;
        }
        
        printf("\n查询结果:\n");
        printf("记录ID\t用户ID\t书名\t借出日期\t\t归还日期\t\t状态\n");
        printf("--------------------------------------------------------------------\n");
        
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            printf("%d\t%d\t%s\t%s\t%s\t%s\n",
                   sqlite3_column_int(stmt, 0),
                   sqlite3_column_int(stmt, 1),
                   sqlite3_column_text(stmt, 2),
                   sqlite3_column_text(stmt, 3),
                   sqlite3_column_text(stmt, 4),
                   sqlite3_column_text(stmt, 5));
        }
        
        sqlite3_finalize(stmt);
    }
}









void AddBook() {
    // 定义变量存储图书信息
    char bookname[100], author[50], publisher[50], category[30];
    int years, num, price;
    
    printf("\n=== 添加新图书 ===\n");
    
    // 获取图书信息
    printf("请输入书名: ");
    scanf(" %[^\n]", bookname);
    
    printf("请输入作者: ");
    scanf(" %[^\n]", author);
    
    printf("请输入出版社: ");
    scanf(" %[^\n]", publisher);
    
    printf("请输入分类: ");
    scanf(" %[^\n]", category);
    
    printf("请输入出版年份: ");
    scanf("%d", &years);
    
    printf("请输入库存数量: ");
    scanf("%d", &num);
    
    printf("请输入价格(分): ");
    scanf("%d", &price);
    
    // 检查书名是否已存在
    char checkSql[256];
    sprintf(checkSql, "SELECT COUNT(*) FROM book WHERE bookname = '%s'", bookname);
    
    sqlite3_stmt *checkStmt;
    if (sqlite3_prepare_v2(db, checkSql, -1, &checkStmt, NULL) != SQLITE_OK) {
        printf("数据库查询错误: %s\n", sqlite3_errmsg(db));
        return;
    }
    
    if (sqlite3_step(checkStmt) == SQLITE_ROW && sqlite3_column_int(checkStmt, 0) > 0) {
        printf("错误: 书名为 %s 的图书已存在!\n", bookname);
        sqlite3_finalize(checkStmt);
        return;
    }
    sqlite3_finalize(checkStmt);
    
    // 插入新图书
    char insertSql[512];
    sprintf(insertSql, 
            "INSERT INTO book (bookname, author, publisher, category, years, num, price, status) "
            "VALUES ('%s', '%s', '%s', '%s', %d, %d, %d, %d)",
            bookname, author, publisher, category, years, num, price, num > 0 ? 1 : 0);
    
    char *errMsg = NULL;
    if (sqlite3_exec(db, insertSql, NULL, NULL, &errMsg) != SQLITE_OK) {
        printf("添加图书失败: %s\n", errMsg);
        sqlite3_free(errMsg);
    } else {
        printf("图书添加成功! 图书ID: %lld\n", sqlite3_last_insert_rowid(db));
    }
}
  
   


void ModifyBookInfo() {
    int bookId;
    printf("\n=== 修改图书信息 ===\n");
    printf("请输入要修改的图书ID: ");
    scanf("%d", &bookId);
    
    // 先查询图书是否存在
    char selectSql[256];
    sprintf(selectSql, "SELECT bookname, author, publisher, category, years, num, price FROM book WHERE id = %d", bookId);
    
    sqlite3_stmt *stmt;
    if (sqlite3_prepare_v2(db, selectSql, -1, &stmt, NULL) != SQLITE_OK) {
        printf("数据库查询错误: %s\n", sqlite3_errmsg(db));
        return;
    }
    
    if (sqlite3_step(stmt) != SQLITE_ROW) {
        printf("未找到ID为%d的图书!\n", bookId);
        sqlite3_finalize(stmt);
        return;
    }
    
    // 显示当前信息
    printf("\n当前图书信息:\n");
    printf("1. 书名: %s\n", sqlite3_column_text(stmt, 0));
    printf("2. 作者: %s\n", sqlite3_column_text(stmt, 1));
    printf("3. 出版社: %s\n", sqlite3_column_text(stmt, 2));
    printf("4. 分类: %s\n", sqlite3_column_text(stmt, 3));
    printf("5. 出版年份: %d\n", sqlite3_column_int(stmt, 4));
    printf("6. 库存: %d\n", sqlite3_column_int(stmt, 5));
    printf("7. 价格: %d分\n", sqlite3_column_int(stmt, 6));
    
    sqlite3_finalize(stmt);
    
    // 获取修改后的信息
    char newBookname[100], newAuthor[50], newPublisher[50], newCategory[30];
    int newYears, newNum, newPrice;
    
    printf("\n请输入新的信息(不修改请直接回车):\n");
    
    printf("书名: ");
    scanf(" %[^\n]", newBookname);
    
    printf("作者: ");
    scanf(" %[^\n]", newAuthor);
    
    printf("出版社: ");
    scanf(" %[^\n]", newPublisher);
    
    printf("分类: ");
    scanf(" %[^\n]", newCategory);
    
    printf("出版年份: ");
    char yearsInput[10];
    scanf(" %s", yearsInput);
    newYears = atoi(yearsInput);
    
    printf("库存: ");
    char numInput[10];
    scanf(" %s", numInput);
    newNum = atoi(numInput);
    
    printf("价格(分): ");
    char priceInput[10];
    scanf(" %s", priceInput);
    newPrice = atoi(priceInput);
    
    // 构建更新SQL语句
    char updateSql[1024];
    sprintf(updateSql, 
            "UPDATE book SET "
            "bookname = CASE WHEN '%s' = '' THEN bookname ELSE '%s' END, "
            "author = CASE WHEN '%s' = '' THEN author ELSE '%s' END, "
            "publisher = CASE WHEN '%s' = '' THEN publisher ELSE '%s' END, "
            "category = CASE WHEN '%s' = '' THEN category ELSE '%s' END, "
            "years = CASE WHEN %d = 0 THEN years ELSE %d END, "
            "num = CASE WHEN %d = 0 THEN num ELSE %d END, "
            "price = CASE WHEN %d = 0 THEN price ELSE %d END, "
            "status = CASE WHEN %d = 0 THEN status ELSE %d END "
            "WHERE id = %d",
            newBookname, newBookname,
            newAuthor, newAuthor,
            newPublisher, newPublisher,
            newCategory, newCategory,
            newYears, newYears,
            newNum, newNum,
            newPrice, newPrice,
            newNum, newNum > 0 ? 1 : 0,
            bookId);
    
    char *errMsg = NULL;
    if (sqlite3_exec(db, updateSql, NULL, NULL, &errMsg) != SQLITE_OK) {
        printf("修改图书信息失败: %s\n", errMsg);
        sqlite3_free(errMsg);
    } else {
        printf("图书信息修改成功!\n");
    }
}


void DeleteBookInfo() {
    int bookId;
    printf("\n=== 删除图书 ===\n");
    printf("请输入要删除的图书ID: ");
    scanf("%d", &bookId);
    
    // 先检查图书是否存在
    char checkSql[256];
    sprintf(checkSql, "SELECT bookname FROM book WHERE id = %d", bookId);
    
    sqlite3_stmt *checkStmt;
    if (sqlite3_prepare_v2(db, checkSql, -1, &checkStmt, NULL) != SQLITE_OK) {
        printf("数据库查询错误: %s\n", sqlite3_errmsg(db));
        return;
    }
    
    if (sqlite3_step(checkStmt) != SQLITE_ROW) {
        printf("未找到ID为%d的图书!\n", bookId);
        sqlite3_finalize(checkStmt);
        return;
    }
    
    char bookname[100];
    strcpy(bookname, (const char*)sqlite3_column_text(checkStmt, 0));
    sqlite3_finalize(checkStmt);
    
    // 确认删除
    printf("确定要删除图书《%s》(ID: %d)吗？(y/n): ", bookname, bookId);
    char confirm;
    scanf(" %c", &confirm);
    
    if (confirm != 'y' && confirm != 'Y') {
        printf("取消删除操作\n");
        return;
    }
    
    // 执行删除
    char deleteSql[256];
    sprintf(deleteSql, "DELETE FROM book WHERE id = %d", bookId);
    
    char *errMsg = NULL;
    if (sqlite3_exec(db, deleteSql, NULL, NULL, &errMsg) != SQLITE_OK) {
        printf("删除图书失败: %s\n", errMsg);
        sqlite3_free(errMsg);
    } else {
        printf("图书删除成功!\n");
    }
}



void SearchBookInfo() {
    int choice;
    char keyword[100];
    
    printf("\n=== 图书查询 ===\n");
    printf("1. 按书名查询\n");
    printf("2. 按作者查询\n");
    printf("3. 按出版社查询\n");
    printf("4. 按分类查询\n");
    printf("5. 按出版年份查询\n");
    printf("请选择查询方式: ");
    scanf("%d", &choice);
    clearInputBuffer();
    
    if (choice < 1 || choice > 5) {
        printf("无效的选择!\n");
        return;
    }
    
    printf("请输入查询关键词: ");
    scanf(" %[^\n]", keyword);
    
    // 构建查询SQL
    char querySql[512];
    const char *field;
    
    switch (choice) {
        case 1: field = "bookname"; break;
        case 2: field = "author"; break;
        case 3: field = "publisher"; break;
        case 4: field = "category"; break;
        case 5: field = "years"; break;
        default: return;
    }
    
    if (choice == 5) {
        // 按年份精确查询
        sprintf(querySql, "SELECT * FROM book WHERE %s = %s", field, keyword);
    } else {
        // 其他字段模糊查询
        sprintf(querySql, "SELECT * FROM book WHERE %s LIKE '%%%s%%'", field, keyword);
    }
    
    sqlite3_stmt *stmt;
    if (sqlite3_prepare_v2(db, querySql, -1, &stmt, NULL) != SQLITE_OK) {
        printf("数据库查询错误: %s\n", sqlite3_errmsg(db));
        return;
    }
    
    printf("\n查询结果:\n");
    printf("ID\t书名\t作者\t出版社\t分类\t年份\t库存\t价格\t状态\n");
    printf("--------------------------------------------------------------------\n");
    
    int found = 0;
    while (sqlite3_step(stmt) == SQLITE_ROW) {
        printf("%d\t%s\t%s\t%s\t%s\t%d\t%d\t%d.%02d\t%s\n",
               sqlite3_column_int(stmt, 0),
               sqlite3_column_text(stmt, 1),
               sqlite3_column_text(stmt, 2),
               sqlite3_column_text(stmt, 3),
               sqlite3_column_text(stmt, 4),
               sqlite3_column_int(stmt, 5),
               sqlite3_column_int(stmt, 6),
               sqlite3_column_int(stmt, 7) / 100,
               sqlite3_column_int(stmt, 7) % 100,
               sqlite3_column_int(stmt, 8) == 1 ? "可借" : "不可借");
        found++;
    }
    
    if (found == 0) {
        printf("未找到匹配的图书!\n");
    }
    
    sqlite3_finalize(stmt);
}




/**
 * @brief 添加书评
 * @param username 用户名
 */
void addReview(const char *username) {
    if (!username) {
        printf("无效的用户名\n");
        return;
    }

    // 获取用户输入的书名
    char bookname[MAX_bookname_LEN];
    printf("请输入要评论的书名: ");
    fgets(bookname, sizeof(bookname), stdin);
    bookname[strcspn(bookname, "\n")] = '\0';

    // 获取书籍ID
    sqlite3_stmt *stmt;
    char sql[512];
    snprintf(sql, sizeof(sql), "SELECT id FROM book WHERE bookname = '%s'", bookname);
    
    if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK) {
        printf("数据库错误: %s\n", sqlite3_errmsg(db));
        return;
    }

    int book_id = -1;
    if (sqlite3_step(stmt) == SQLITE_ROW) {
        book_id = sqlite3_column_int(stmt, 0);
    }
    sqlite3_finalize(stmt);

    if (book_id == -1) {
        printf("未找到书籍: %s\n", bookname);
        return;
    }

    // 获取用户ID
    snprintf(sql, sizeof(sql), "SELECT id FROM user WHERE username = '%s'", username);
    if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK) {
        printf("数据库错误: %s\n", sqlite3_errmsg(db));
        return;
    }

    int user_id = -1;
    if (sqlite3_step(stmt) == SQLITE_ROW) {
        user_id = sqlite3_column_int(stmt, 0);
    }
    sqlite3_finalize(stmt);

    if (user_id == -1) {
        printf("用户不存在\n");
        return;
    }

    // 获取评论内容
    char content[MAX_REVIEW_CONTENT];
    printf("请输入评论内容(最多%d字符): ", MAX_REVIEW_CONTENT);
    fgets(content, sizeof(content), stdin);
    content[strcspn(content, "\n")] = '\0';

    // 获取评分
    int rating;
    printf("请输入评分(1-5星): ");
    scanf("%d", &rating);
    while(getchar() != '\n'); // 清除输入缓冲区

    if (rating < 1 || rating > 5) {
        printf("评分必须在1-5之间\n");
        return;
    }

    // 获取当前时间
    time_t review_time = time(NULL);

    // 插入评论
    const char *insert_sql = "INSERT INTO review (user_id, book_id, username, content, rating, review_time) "
                           "VALUES (?, ?, ?, ?, ?, ?)";
    
    if (sqlite3_prepare_v2(db, insert_sql, -1, &stmt, NULL) != SQLITE_OK) {
        printf("数据库错误: %s\n", sqlite3_errmsg(db));
        return;
    }

    sqlite3_bind_int(stmt, 1, user_id);
    sqlite3_bind_int(stmt, 2, book_id);
    sqlite3_bind_text(stmt, 3, username, -1, SQLITE_STATIC);
    sqlite3_bind_text(stmt, 4, content, -1, SQLITE_STATIC);
    sqlite3_bind_int(stmt, 5, rating);
    sqlite3_bind_int64(stmt, 6, review_time);

    if (sqlite3_step(stmt) != SQLITE_DONE) {
        printf("添加评论失败: %s\n", sqlite3_errmsg(db));
    } else {
        printf("评论添加成功!\n");
    }

    sqlite3_finalize(stmt);
}

/**
 * @brief 查看书籍评论
 * @param bookname 书名
 */
void viewBookReviews(const char *bookname) {
    if (!bookname) {
        printf("无效的书名\n");
        return;
    }

    printf("\n===== 书籍《%s》的评论 =====\n", bookname);

    sqlite3_stmt *stmt;
    const char *sql = "SELECT r.username, r.content, r.rating, r.review_time "
                     "FROM review r JOIN book b ON r.book_id = b.id "
                     "WHERE b.bookname = ? "
                     "ORDER BY r.review_time DESC";

    if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK) {
        printf("数据库错误: %s\n", sqlite3_errmsg(db));
        return;
    }

    sqlite3_bind_text(stmt, 1, bookname, -1, SQLITE_STATIC);

    int has_reviews = 0;
    while (sqlite3_step(stmt) == SQLITE_ROW) {
        has_reviews = 1;
        const char *username = (const char *)sqlite3_column_text(stmt, 0);
        const char *content = (const char *)sqlite3_column_text(stmt, 1);
        int rating = sqlite3_column_int(stmt, 2);
        time_t review_time = sqlite3_column_int64(stmt, 3);
        
        char time_str[20];
        strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", localtime(&review_time));
        
        printf("\n用户: %s\n", username);
        printf("评分: %d/5\n", rating);
        printf("时间: %s\n", time_str);
        printf("内容: %s\n", content);
    }

    if (!has_reviews) {
        printf("暂无评论\n");
    }

    sqlite3_finalize(stmt);
}

/**
 * @brief 查看用户评论
 * @param username 用户名
 */
void viewUserReviews(const char *username) {
    if (!username) {
        printf("无效的用户名\n");
        return;
    }

    printf("\n===== 用户 %s 的评论 =====\n", username);

    sqlite3_stmt *stmt;
    const char *sql = "SELECT b.bookname, r.content, r.rating, r.review_time "
                     "FROM review r JOIN book b ON r.book_id = b.id "
                     "WHERE r.username = ? "
                     "ORDER BY r.review_time DESC";

    if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK) {
        printf("数据库错误: %s\n", sqlite3_errmsg(db));
        return;
    }

    sqlite3_bind_text(stmt, 1, username, -1, SQLITE_STATIC);

    int has_reviews = 0;
    while (sqlite3_step(stmt) == SQLITE_ROW) {
        has_reviews = 1;
        const char *bookname = (const char *)sqlite3_column_text(stmt, 0);
        const char *content = (const char *)sqlite3_column_text(stmt, 1);
        int rating = sqlite3_column_int(stmt, 2);
        time_t review_time = sqlite3_column_int64(stmt, 3);
        
        char time_str[20];
        strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", localtime(&review_time));
        
        printf("\n书籍: %s\n", bookname);
        printf("评分: %d/5\n", rating);
        printf("时间: %s\n", time_str);
        printf("内容: %s\n", content);
    }

    if (!has_reviews) {
        printf("暂无评论\n");
    }

    sqlite3_finalize(stmt);
}


/**
 * @brief 列出所有图书信息
 */
void listAllBooks() {
    printf("\n==== 所有图书信息 ====\n");
    
    sqlite3_stmt *stmt;
    const char *sql = "SELECT id, bookname, author, publisher, category, years, num, price, status FROM book ORDER BY id";
    
    if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK) {
        printf("数据库错误: %s\n", sqlite3_errmsg(db));
        return;
    }
    
    // 打印表头
    printf("%-5s %-30s %-20s %-20s %-15s %-6s %-4s %-8s %-10s\n", 
           "ID", "书名", "作者", "出版社", "分类", "年份", "数量", "价格", "状态");
    printf("----------------------------------------------------------------------------------------------------------------\n");
    
    int count = 0;
    while (sqlite3_step(stmt) == SQLITE_ROW) {
        count++;
        int id = sqlite3_column_int(stmt, 0);
        const char *bookname = (const char *)sqlite3_column_text(stmt, 1);
        const char *author = (const char *)sqlite3_column_text(stmt, 2);
        const char *publisher = (const char *)sqlite3_column_text(stmt, 3);
        const char *category = (const char *)sqlite3_column_text(stmt, 4);
        int years = sqlite3_column_int(stmt, 5);
        int num = sqlite3_column_int(stmt, 6);
        int price = sqlite3_column_int(stmt, 7);
        int status = sqlite3_column_int(stmt, 8);
        
        // 格式化价格显示
        char price_str[20];
        snprintf(price_str, sizeof(price_str), "%.2f", price / 100.0);
        
        // 状态文字
        const char *status_str;
        switch(status) {
            case 0: status_str = "不可借"; break;
            case 1: status_str = "可借"; break;
            case 2: status_str = "已借出"; break;
            default: status_str = "未知"; break;
        }
        
        printf("%-5d %-30s %-20s %-20s %-15s %-6d %-4d %-8s %-10s\n", 
               id, bookname, author, publisher, category, years, num, price_str, status_str);
    }
    
    if (count == 0) {
        printf("图书馆中没有图书!\n");
    } else {
        printf("\n共找到 %d 本图书\n", count);
    }
    
    sqlite3_finalize(stmt);
}